﻿package net.wangit.user.org;

import java.util.Map;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.framework.util.MapListUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.user.privilege.PrivilegeUtil;
import net.wangit.util.Checker;


public class OrgFactory {

	private static final String SQL_ORG = "select * from AORG where orgid=?";
	private static final String SQL_ROLES = "select * from AORGROLE where orgid=?";
	private static final String SQL_PRIVILEGES = "select * from AROLEPRIVILEGE where roleid not in (select roleid from AROLE where enabled=0) and roleid in (select roleid from AORGROLE where orgid=?)";

	public OrgFactory() {
	}

	public static Org getOrg(String oid) throws Exception {
		Org organization = OrgCache.get(oid);
		if (organization == null) {
			organization = createOrg(oid);
			OrgCache.put(oid, organization);
		}
		return organization;
	}

	private static Org createOrg(String oid) throws Exception {
		DB db = DBFactory.getDB();
		MapList list = db.query("select * from AORG where orgid=?", oid, 2);
		if (Checker.isEmpty(list)) {
			return null;
		} else {
			Row row = list.getRow(0);
			Org org = new Org(oid);
			org.setName(row.get("orgname"));
			org.setProperties(row.toMap());
			org.setRoles(getRoles(db, oid));
			org.setPrivileges(getPrivileges(db, oid));
			return org;
		}
	}

	private static String[] getRoles(DB db, String oid) throws Exception {
		MapList list = db.query("select * from AORGROLE where orgid=?", oid, 2);
		return MapListUtil.getArray(list, "roleid");
	}

	private static Map getPrivileges(DB db, String oid) throws Exception {
		MapList list = db
				.query(
						"select * from AROLEPRIVILEGE where roleid not in (select roleid from AROLE where enabled=0) and roleid in (select roleid from AORGROLE where orgid=?)",
						oid, 2);
		return PrivilegeUtil.getPrivileges(list);
	}
}
